package App.Service;

import App.Model.Account.CrmUser;
import App.Model.BaseEnum;
import App.Model.Chat.CrmChatGroup;
import App.Model.Friend.FriendMeResponse;
import App.Model.PageSummary;
import App.Model.Task.*;
import App.Repository.*;
import com.alibaba.fastjson.JSONObject;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import App.Model.Chat.CrmChatGroup;
import App.Model.Project.*;
import App.Repository.ChatRepository;
import App.Repository.ProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigInteger;
import java.util.List;

/**
 * Created by xw on 2018/11/30.
 */
@Service
public class TaskService {

    @Autowired
    TecentIMService _imService;

    @Autowired
    private TaskRepository _repository;
    @Autowired
    CommonRepository _commonRepository;

    @Autowired
    private FriendRepository friendRepository;

    //任务列表
    public List<TaskInfoList> getTaskList(TaskListRequest _request, int userid) {
        return _repository.getTaskListResponse(_request, userid);
    }

    public ResultResponse insertTask(TaskSaveRequest _request, String taskid, int userid) throws Exception {
        //  if (_request.getTaskid() == null || _request.getTaskid().equals("")) {
        return _repository.insertTask(_request, taskid, userid);
        //} else {
        //   return _repository.updateTask(_request, userid);
        //  }
    }

    public TaskGetDetailResponse getTaskDetail(TaskGetDetailRequest _request, int userid) {
        return _repository.getTaskDetail(_request, userid);
    }

    public List<TaskAheadType> getAheadTypeResponse() {
        return _repository.getAheadTypeResponse();
    }

    public List<TaskRepeatType> getTaskRepeatTypeResponse() {
        return _repository.getTaskRepeatTypeResponse();
    }

    public int deleteTask(TaskDeleteRequest _request, int userid) {
        return _repository.deleteTask(_request, userid);
    }

    public int completeTask(TaskCompleteRequest _request, int userid) throws Exception {
        return completeTaskSimple(_request, userid);
    }

    public int completeTaskSimple(TaskCompleteRequest _request, int userid) throws Exception {
        int result = 0;
        try {
            String taskid = _request.getTaskid();
            result = _repository.completeTaskSimple(_request, userid);
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _userNmae = _theUser.getRealname();
            if (result > 0) {
                List<CrmTask> _taskList = _repository.getTaskInfo(taskid);
                String _taskContent = "";
                if (_taskList != null && _taskList.size() > 0) {
                    _taskContent = _taskList.get(0).getContent();
                }

                //用于判断是否是完成本任务
                String flat = "1";

                String _content = "";
                FriendMeResponse userInfo = friendRepository.getUserInfo(userid);
                List<CrmTaskProjectRelation> _projectRelations = _repository.getTaskProjectRelation(taskid);
                if (_projectRelations != null && _projectRelations.size() > 0) {
                    _content = String.format("%s已完成任务：%s", _userNmae, _taskContent);
                    flat = "2";
                } else {
                    _content = String.format("%s已完成本任务", _userNmae);
                }

                List<CrmTaskMember> _savedTaskMembers = _repository.getTaskMembers(taskid);
                List<TaskMember> _taskMembers = new ArrayList<>();
                for (CrmTaskMember m : _savedTaskMembers) {
                    TaskMember _tm = _repository.toCrmTaskMember(m);
                    _taskMembers.add(_tm);
                }

                JSONObject obj = new JSONObject();
                JSONObject data = new JSONObject();
                obj.put("type", "system");

                data.put("type", BaseEnum.ChatType.Task.getChatType());
                data.put("taskid", taskid);
                data.put("stagestatus", BaseEnum.StageStatus.Complete.getStageStatus());
                String _projectid = "";
                List<CrmTaskProjectRelation> _projectTasks = _repository.getTaskProjectRelation(taskid);
                if (_projectTasks != null && _projectTasks.size() > 0) {
                    _projectid = _projectTasks.get(0).getProjectid();
                }
                data.put("projectid", _projectid);
                obj.put("data", data);

                _repository.sendIMGroupMessageForTaskExtJsonObject(taskid, _content, _taskMembers, userid, obj);
                if("1".equals(flat)){
                    _repository.sendIMGroupMessageForTaskExtJsonObject(taskid, "群聊已关闭，如需在本群聊天，请重启本任务", _taskMembers, userid, obj);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    public int pauseTask(TaskPauseRequest _request, int userid) {
        return _repository.pauseTask(_request, userid);
    }

    public int restartTask(TaskRestartRequest _request, int userid) throws Exception {
        return restartTaskSimple(_request, userid);
    }

    public int restartTaskSimple(TaskRestartRequest _request, int userid) throws Exception {
        int result = 0;
        try {
            String taskid = _request.getTaskid();
            result = _repository.restartTaskSimple(_request, userid);
            if (result > 0) {
                List<CrmTask> _taskList = _repository.getTaskInfo(taskid);
                String _taskContent = "";
                if (_taskList != null && _taskList.size() > 0) {
                    _taskContent = _taskList.get(0).getContent();
                }
                String _content = String.format("任务：%s 已重启", _taskContent);

                JSONObject obj = new JSONObject();
                JSONObject data = new JSONObject();
                obj.put("type", "system");

                data.put("type", BaseEnum.ChatType.Task.getChatType());
                data.put("taskid", taskid);
                data.put("stagestatus", BaseEnum.StageStatus.Start.getStageStatus());
                String _projectid = "";
                List<CrmTaskProjectRelation> _projectTasks = _repository.getTaskProjectRelation(taskid);
                if (_projectTasks != null && _projectTasks.size() > 0) {
                    _projectid = _projectTasks.get(0).getProjectid();
                }
                data.put("projectid", _projectid);
                obj.put("data", data);

                List<CrmTaskMember> _savedTaskMembers = _repository.getTaskMembers(taskid);
                List<TaskMember> _taskMembers = new ArrayList<>();
                for (CrmTaskMember m : _savedTaskMembers) {
                    TaskMember _tm = _repository.toCrmTaskMember(m);
                    _taskMembers.add(_tm);
                }
                _repository.sendIMGroupMessageForTaskExtJsonObject(taskid, _content, _taskMembers, userid, obj);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    public int transferManager(TaskTransferManagerRequest _request, int userid) {
        return _repository.transferManager(_request, userid);
    }


    public int transferHost(TaskTransferHostRequest _request, int userid) {
        return _repository.transferHost(_request, userid);
    }

    public int taskFileMerge(TaskFileMergeRequest _request, int userid) {
        return _repository.taskFileMerge(_request, userid);
    }


    public int insertFileUploadRecord(String fileid, String oldFileName, String newFileName, String showFileName, String fileSuffix, int userid) {

        return _repository.insertFileUploadRecord(fileid, oldFileName, newFileName, showFileName, fileSuffix, userid);
    }

    public TaskJobInfo getReminderMember(String reminderid) {
        return _repository.getReminderMember(reminderid);
    }


    public ResultResponse saveTaskInfo(SaveTaskInfoRequest _request, int userid) throws Exception {
        return _repository.updateTaskInfo(_request, userid);
    }

    public int saveTaskReminder(SaveTaskReminderRequest _request, int userid) throws Exception {
        return _repository.saveTaskReminder(_request, userid);
    }

    public List<GetTaskForSpecialDayListResponse> getTaskForSepcialDay(int userid) throws Exception {
        return _repository.getTaskForSepcialDay(userid);
    }

    public ResultResponse addTaskMember(AddTaskMemberRequest _request, int userid) {
        return _repository.addTaskMember(_request, userid);
    }


    public int deleteTaskMember(DeleteTaskMemberRequest _request, int userid) {
        return _repository.deleteTaskMember(_request, userid);
    }

    public int setTaskManager(SetTaskManagerRequest _request, int userid) {
        return _repository.setTaskManager(_request, userid);

    }


    public int setTaskHost(SetTaskManagerRequest _request, int userid) {
        return _repository.setTaskHost(_request, userid);

    }

    public int deleteTaskFile(TaskDeleteFileRequest _request, int userid) {
        return _repository.deleteTaskFiles(_request, userid);
    }


    public int renameTaskFile(TaskRenameFileRequest _request, int userid) {
        return _repository.renameTaskFile(_request, userid);
    }

    public int addTaskFile(TaskAddFileRequest _request, int userid) {
        return _repository.addTaskFile(_request, userid);
    }

    public int addTaskFile2(TaskAddFileRequest _request, int userid) {
        return _repository.addTaskFile2(_request, userid);
    }

    public int updateTaskBeginTime(SaveTaskBeginTimeRequest _request, int userid) throws Exception {
        return _repository.updateTaskBeginTime(_request, userid);
    }

    public List<TaskFile> getTaskFiles(GetTaskFileRequest _request, int userid) {
        return _repository.getTaskFiles(_request, userid);
    }


    //把逻辑处理放在service曾,数据层次碎片化
    public GetTaskPageItemsResponse getTaskPageItems(GetTaskPageItemsRequest _request, int userid) {

        List<CrmTask> _tasks = _repository.getCrmTaskPage(_request, userid);
        PageSummary _pageSummary = _repository.getTaskPageCount(_request, userid);
        List<TaskInfo> _taskInfos = _repository.getTaskinfoPage(_tasks, userid);

        GetTaskPageItemsResponse _response = new GetTaskPageItemsResponse();
        _response.setPagecount(_pageSummary);
        _response.setPagedata(_taskInfos);
        return _response;
    }

    public List<TaskInfo> getUnCompletedTasks(TaskListRequest _request, int userid) {
        String _searchKey = _request.getSearchkey();
        List<CrmTask> _tasks = _repository.getUnCompletedTasks(_searchKey, userid);
        return _repository.getTaskinfoPage(_tasks, userid);
    }

    @Transactional
    public int setFileViewed(TaskViewdFileRequest _request,int userid){

        return  _repository.setFileViewed(_request,userid);
    }

    public int delFinishedTaskGroup(CrmUser _request, int userid){
        List<CrmChatGroup> list = _repository.getMyFinishedTaskGroup(_request.getId());
        for (CrmChatGroup _t : list) {
            String groupId = _t.getGroupid();
            _imService.destroyIMGroup(groupId, userid);
        }
        return  1;
    }
}